//
//  ToProfileViewController.m
//  MagazineShangejie
//
//  Created by mac on 15/4/13.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//---------------------------------------------------------
//                    *                *
//                  *      新编辑资料      *
//                    *                *
//---------------------------------------------------------

#import "ToProfileViewController.h"
#import "Util.h"
@interface ToProfileViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    UITableView*tableview;
    NSMutableDictionary*userDict;
}

@end

@implementation ToProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableview];
    // Do any additional setup after loading the view.
}
-(void)initTableview{
    tableview=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableview.delegate=self;
    tableview.dataSource=self;
    [self.view insertSubview:tableview atIndex:0];
    tableview.tableFooterView = [[UIView alloc] init];
//    [self.view addSubview:tableview];
    
    userDict=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults objectForKey:@"user"]];
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 40, 40)];
    [button setTitle:@"保存" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(rightBarButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem=rightBarItem;
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        //        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
        //            [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [buttonf setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
    }
    
    UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
    
}

-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - rightBarButton
-(void)rightBarButton{
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    if ([userDict[@"nickname"] length]<2) {
        [alert setMessage:@"昵称长度过短"];
        [alert show];
        return;
    }
    
    NSString*str_signature;
    if ([userDict[@"signature"] length]>12) {
        str_signature=[userDict[@"signature"] substringToIndex:12];
    }else{
        str_signature=userDict[@"signature"];
    }
    NSDictionary*dic=[NSDictionary dictionaryWithObjectsAndKeys:userDict[@"sex"],@"sex",userDict[@"nickname"],@"nickname",userDict[@"email"],@"email",str_signature,@"signature", nil];
    [SVProgressHUD show];
    [[AppAPIClient sharedClient] POST:@"User/Update" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
//        NSMutableDictionary*dic=[NSMutableDictionary dictionaryWithDictionary:IFUserLogin];
//        [dic setObject:self.nike.text forKey:@"nickname"];
//        [dic setObject:self.emali.text forKey:@"email"];
//        [dic setObject:self.sex forKey:@"sex"];
//        [dic setObject:str_signature forKey:@"signature"];
        [UserDefaults setObject:userDict forKey:@"user"];
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }];
    
}
#pragma mark - tableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 7;
    }else{
        return 2;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 10;
    }else{
        return 0;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topro"];
    if(cell==nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: @"topro"];
        UILabel*Label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width-20,cell.contentView.frame.size.height)];
        Label.textAlignment = NSTextAlignmentRight;
        Label.tag=666;
        [cell.contentView addSubview:Label];
        UIImageView*imageview=[[UIImageView alloc]initWithFrame:CGRectMake(tableView.frame.size.width-60, 2, 40, 40)];
//        imageview.layer.
        [imageview.layer setCornerRadius:20];
        [imageview.layer setMasksToBounds:YES];
        imageview.tag=10;
        [cell.contentView addSubview:imageview];
    }
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:10];
    imageview.image=nil;
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            cell.textLabel.text=@"头像";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.text=@"";
            UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:10];
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:userDict[@"thumb"][@"180"]] options:SDWebImageRefreshCached progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if (image==nil) {
                    [imageview setImage:[UIImage imageNamed:@"icon_default_ipad"]];
                }else{
                    [imageview setImage:image];
                }
            }];
        }else if (indexPath.row==1){
            cell.textLabel.text=@"昵称";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            label.text=userDict[@"nickname"];
        }else if (indexPath.row==2){
            cell.textLabel.text=@"手机";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor grayColor];
            label.text=userDict[@"mobile"];
        }else if (indexPath.row==3){
            cell.textLabel.text=@"性别";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            if ([userDict[@"sex"] intValue]) {
                label.text=@"男";
            }else{
                label.text=@"女";
            }
            
        }else if (indexPath.row==4){
            cell.textLabel.text=@"签名";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            label.text=userDict[@"signature"];
        }else if (indexPath.row==5){
            cell.textLabel.text=@"邮箱";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            label.text=userDict[@"email"];
        }else if (indexPath.row==6){
            cell.textLabel.text=@"修改密码";
        }
    }else{
        if (indexPath.row==0) {
          cell.textLabel.text=@"我的积分";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            label.text=userDict[@"point"];
            
        }else if (indexPath.row==1){
          cell.textLabel.text=@"我的等级";
            UILabel*label=(UILabel*)[cell.contentView viewWithTag:666];
            label.textColor=[UIColor blackColor];
            label.text=[NSString stringWithFormat:@"LV%@",userDict[@"vip"]];
            
        }
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
//            [alert setTitle:@"头像"];
//            [alert setTag:1];
            alert=nil;
            UIAlertView*image=[[UIAlertView alloc]initWithTitle:@"更改头像" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"从相册", @"从相机",nil];
            [image setTag:1];
            [image show];
        }else if (indexPath.row==1){
            [alert setTitle:@"昵称"];
            [alert setTag:2];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            UITextField *nameField = [alert textFieldAtIndex:0];
            nameField.placeholder = @"输入新昵称";
        }else if (indexPath.row==2){
            alert=nil;
             [self performSegueWithIdentifier:@"bangding" sender:self];
            
        }else if (indexPath.row==3){
            alert=nil;
            UIAlertView*sex=[[UIAlertView alloc]initWithTitle:@"性别" message:@"" delegate:self cancelButtonTitle:@"女" otherButtonTitles:@"男",nil];
            [sex setTag:4];
            [sex show];
//            cell.textLabel.text=@"性别";
        }else if (indexPath.row==4){
            [alert setTitle:@"签名"];
            [alert setTag:5];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            UITextField *nameField = [alert textFieldAtIndex:0];
            nameField.placeholder = @"输入新签名";
        }else if (indexPath.row==5){
            [alert setTitle:@"邮箱"];
            [alert setTag:6];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            UITextField *nameField = [alert textFieldAtIndex:0];
            nameField.placeholder = @"输入新邮箱";
        }else if (indexPath.row==6){
            [alert setTitle:@"修改密码"];
            [alert setTag:7];
            [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
            UITextField *nameField = [alert textFieldAtIndex:0];
            nameField.placeholder = @"输入新密码";
        }
    }else{
        alert=nil;
        if (indexPath.row==0) {
            
//            cell.textLabel.text=@"我的积分";
        }else if (indexPath.row==1){
//            cell.textLabel.text=@"我的等级";
        }
    }
    [alert show];
}
#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag!=4 && buttonIndex == 0){
        return;
    }
    if(alertView.tag == 1){
        if(buttonIndex == 1){
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            //imagePickerController.modalPresentationStyle   = UIModalPresentationCurrentContext;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing            = YES;
            //imagePickerController.showsCameraControls = NO;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }else if(buttonIndex == 2){
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            //imagePickerController.modalPresentationStyle   = UIModalPresentationCurrentContext;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing            = YES;
            imagePickerController.showsCameraControls = YES;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }else{
            [alertView dismissWithClickedButtonIndex:0 animated:YES];
        }
    }else if(alertView.tag == 2){
        if ([alertView textFieldAtIndex:0].text.length>2) {
            [userDict setValue:[alertView textFieldAtIndex:0].text forKey:@"nickname"];
        }else{
            [SVProgressHUD showErrorWithStatus:@"昵称过短"];
            return;
        }
        
    }else if(alertView.tag == 4){
        if (buttonIndex == 1) {
            [userDict setValue:@"1" forKey:@"sex"];
        }else{
            [userDict setValue:@"0" forKey:@"sex"];
        }
        
    }else if(alertView.tag == 5){
        
        if ([alertView textFieldAtIndex:0].text.length<=12) {
            [userDict setValue:[alertView textFieldAtIndex:0].text forKey:@"signature"];
            
        }else if ([alertView textFieldAtIndex:0].text.length>12) {
            [SVProgressHUD showErrorWithStatus:@"签名过长,请输入最大12字"];
            return;
        }
        
    }else if(alertView.tag == 6){
        if ([[alertView textFieldAtIndex:0].text length]<2){
            [SVProgressHUD showErrorWithStatus:@"邮箱过短"];
            return;
        }else if (![CommonHelper isValidateEmail:[alertView textFieldAtIndex:0].text]){
            [SVProgressHUD showErrorWithStatus:@"邮箱格式不正确"];
            return;
        }
        [userDict setValue:[alertView textFieldAtIndex:0].text forKey:@"email"];
        

    }else if(alertView.tag == 7){
           if (![[alertView textFieldAtIndex:0].text isEqualToString:[alertView textFieldAtIndex:1].text]) {
            [SVProgressHUD showErrorWithStatus:@"两次输入的密码不匹配"];
            return;
           }

        
        if ([alertView textFieldAtIndex:0].text.length>0) {
            [[AppAPIClient sharedClient] POST:@"User/Update" parameters:@{@"password":[alertView textFieldAtIndex:0].text} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [SVProgressHUD showSuccessWithStatus:@"密码修改成功"];
//                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"ERR: %@",operation.responseString);
                [SVProgressHUD showErrorWithStatus:@"修改失败"];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        }
        
    }
    [tableview reloadData];
}
#pragma mark - imagePickerDelegeta
- (void)uploadUserhead:(UIImage*)image{
    
    [[AppAPIClient sharedClient] POST:@"User/UploadAvatar" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success:%@",responseObject);
        NSString *url = [NSString stringWithFormat:@"%@",[UserDefaults objectForKey:@"user"][@"thumb"][@"180"]];
        [[SDImageCache sharedImageCache] removeImageForKey:url];
        [[SDImageCache sharedImageCache] storeImage:image forKey:url];

//        [self.navigationController popViewControllerAnimated:YES];
        [SVProgressHUD showSuccessWithStatus:LOADING_TEXT_SUCCESS];
        [tableview reloadData];
//        [self dismissViewControllerAnimated:YES completion:^{
//            
//        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error:%@ => %@",operation.responseString,error);
        [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
//        [self dismissViewControllerAnimated:YES completion:NULL];
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        [SVProgressHUD show];
        UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];
        [self uploadUserhead:image];
    }];
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //[self popoverPresentationController];
    [self dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -

- (IBAction)exit:(id)sender {
    //AppDelegate*app=APPDelegate;
    //app.BadgeStr=@"0";
    [[AppAPIClient sharedClient] setTokenA:@""];
//    [UserDefaults removeObjectForKey:@"listTop"];
    //[BPush delTag:[UserDefaults objectForKey:@"token"]];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"usDic"];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Goodaaaccc"];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Diamondaaaccc"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark -
-(void)viewWillAppear:(BOOL)animated{
//    if (tableview!=nil) {
      [tableview reloadData];
//    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
